﻿using HaiFengShop.Entity;
using HaiFengShop.ORM;
using HaiFengShop.ORM.Models;
using HaiFengShop.Tools;
using HaiFengShop.Tools.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HaiFengShop.Service
{
    public class CartService : BaseServer<tb_cart>
    {
        private readonly ResponseMessage res;
        private readonly int uid;
        public CartService(GenericJwtToken genericJwtToken,
            ResponseMessage responseMessage,
             SugarDbContext sugarDbContext) : base(sugarDbContext.Db)
        {
            this.uid = genericJwtToken.Uid;
            this.res = responseMessage;
        }

        public void AddCartInfo(Dictionary<string, object> obj)
        {

            try
            {
                int addType = int.Parse(obj["addType"].ToString());
                int goodsId = int.Parse(obj["goodsId"].ToString());
                int number = int.Parse(obj["number"].ToString());
                int productId = int.Parse(obj["productId"].ToString());
                double currentTime = DateTimeExtensions.ConvertToUnixTimestamp(DateTime.Now);

                // 判断商品是否可以购买
                tb_goods tg = Context.Queryable<tb_goods>()
                    .Where(s => s.id == goodsId)
                    .First();
                if (tg == null || tg.is_on_sale == 0)
                {
                    res.errno = 400;
                    res.errmsg = "商品已下架";
                    return;
                }

                // 取得规格的信息,判断规格库存
                tb_product tp = Context.Queryable<tb_product>()
                    .Where(s => s.id == productId)
                    .First();
                if (tp == null || tp.goods_number < number)
                {
                    res.errno = 400;
                    res.errmsg = "库存不足";
                    return;
                }
                decimal retail_price = (decimal)tp.retail_price;

                if (addType == 1)
                {
                    tb_cart tc = Context.Queryable<tb_cart>()
                      .Where(s => s.user_id == uid && s.is_delete == 0)
                      .First();
                    if (tc != null)
                    {
                        tc.@checked = 0;
                        Update(tc);
                    }


                    string[] listGoodsSpecification = { };
                    if (!string.IsNullOrEmpty(tp.goods_specification_ids))
                    {
                        listGoodsSpecification = Context.Queryable<tb_goods_specification>()
                          .Where(s => s.goods_id == tp.goods_id && s.is_delete == 0)
                          .In(s => s.id, tp.goods_specification_ids.Split('_'))
                          .Select(s => s.value).ToArray();
                    }
                    tb_cart cartData = new tb_cart()
                    {
                        goods_id = tp.goods_id,
                        product_id = productId,
                        goods_sn = tp.goods_sn,
                        goods_name = tg.name,
                        goods_aka = tp.goods_name,
                        goods_weight = tp.goods_weight,
                        freight_template_id = (int)tg.freight_template_id,
                        list_pic_url = tg.list_pic_url,
                        number = number,
                        user_id = uid,
                        retail_price = retail_price,
                        add_price = retail_price,
                        goods_specifition_name_value = string.Join(";", listGoodsSpecification),
                        goods_specifition_ids = tp.goods_specification_ids,
                        @checked = 1,
                        add_time = (int)currentTime,
                        is_fast = 1
                    };
                    Insert(cartData);

                }
                else
                {
                    // 判断购物车中是否存在此规格商品
                    tb_cart tc = Context.Queryable<tb_cart>()
                       .Where(s => s.user_id == uid && s.product_id == productId && s.is_delete == 0)
                       .First();
                    if (tc == null)
                    {
                        // 添加操作
                        // 添加规格名和值
                        string[] listGoodsSpecification = { };
                        if (!string.IsNullOrEmpty(tp.goods_specification_ids))
                        {
                            listGoodsSpecification = Context.Queryable<tb_goods_specification>()
                              .Where(s => s.goods_id == tp.goods_id && s.is_delete == 0)
                              .In(s => s.id, tp.goods_specification_ids.Split('_'))
                              .Select(s => s.value).ToArray();
                        }

                        Insert(new tb_cart()
                        {
                            goods_id = tp.goods_id,
                            product_id = productId,
                            goods_sn = tp.goods_sn,
                            goods_name = tg.name,
                            goods_aka = tp.goods_name,
                            goods_weight = tp.goods_weight,
                            freight_template_id = (int)tg.freight_template_id,
                            list_pic_url = tg.list_pic_url,
                            number = number,
                            user_id = uid,
                            retail_price = retail_price,
                            add_price = retail_price,
                            goods_specifition_name_value = string.Join(";", listGoodsSpecification),
                            goods_specifition_ids = tp.goods_specification_ids,
                            @checked = 1,
                            add_time = (int)currentTime
                        });

                    }
                    else
                    {
                        // 如果已经存在购物车中，则数量增加
                        if (tp.goods_number < (number + tc.number))
                        {
                            res.errno = 400;
                            res.errmsg = "库存都不够啦";
                            return;
                        }
                        tc = Context.Queryable<tb_cart>()
                       .Where(s => s.id == tc.id && s.product_id == productId && s.is_delete == 0 && s.user_id == uid)
                       .First();

                        tc.retail_price = retail_price;

                        tc.number += number;
                        Update(tc);
                    }


                }

            }
            catch (Exception ex)
            {
                res.errno = -1;
                res.errmsg = ex.Message;
                throw ex;
            }
        }

        public void CheckedData(DTOCheckedData checkedData)
        {
            try
            {
                if (string.IsNullOrEmpty(checkedData.productIds))
                {
                    res.errmsg = "选择错误";
                    res.errno = -1;
                    return;
                }
                var tc = Context.Queryable<tb_cart>()
                      .In(s => s.product_id, checkedData.productIds.Split(','))
                      .Where(s => s.is_delete == 0 && s.user_id == uid)
                      .ToList();
                foreach (tb_cart cart in tc)
                {
                    cart.@checked = checkedData.isChecked;
                    Update(cart);
                }
            }
            catch (Exception ex)
            {
                res.errno = -1;
                res.errmsg = ex.Message;
                throw ex;
            }
        }

        public ResponseMessage CheckOrderInfo(int addressId, int addType, int orderFrom, int type)
        {
            try
            {
                int goodsCount = 0; // 购物车的数量
                decimal? goodsMoney = 0; // 购物车的总价
                decimal? freightPrice = 0;
                int outStock = 0;
                DTOCart cartData = new DTOCart();
                // 获取要购买的商品
                if (type == 0)
                {
                    if (addType == 0)
                    {
                        cartData = GetCart(0);
                    }
                    else if (addType == 1)
                    {
                        cartData = GetCart(1);
                    }
                    else if (addType == 2)
                    {
                        cartData = getAgainCart(orderFrom);
                    }
                }
                var checkedGoodsList = cartData.listCart.Where(s => s.@checked == 1).ToList();
                foreach (var item in checkedGoodsList)
                {
                    goodsCount = goodsCount + item.number.Value;
                    goodsMoney = goodsMoney + item.number * item.retail_price.Value;
                    //Context.Queryable<tb_goods>()
                    //    .Where(s=>s.id==)
                    if (item.number <= 0 || item.is_on_sale == 0)
                    {
                        outStock += 1;
                    }
                }
                if (addType == 2)
                {
                    var againGoods = Context.Queryable<tb_order_goods>()
                        .Where(s => s.order_id == orderFrom)
                        .ToList();
                    int againGoodsCount = 0;

                    foreach (var item in againGoods)
                    {
                        againGoodsCount += item.number.Value;
                    }
                    if (goodsCount != againGoodsCount)
                    {
                        outStock = 1;
                    }
                }

                // 选择的收货地址
                tb_address checkedAddress = null;
                if (addressId == 0)
                {
                    checkedAddress = Context.Queryable<tb_address>()
                        .Where(s => s.is_default == 1 && s.user_id == uid && s.is_delete == 0)
                        .First();
                }
                else
                {
                    checkedAddress = Context.Queryable<tb_address>()
                            .Where(s => s.id == addressId && s.user_id == uid && s.is_delete == 0)
                            .First();
                }
                if (checkedAddress != null)
                {
                    // 运费开始
                    // 先将促销规则中符合满件包邮或者满金额包邮的规则找到；
                    // 先看看是不是属于偏远地区。
                    int province_id = checkedAddress.province_id.Value;
                    // 得到数组了，然后去判断这两个商品符不符合要求
                    // 先用这个goods数组去遍历
                    var cartGoods = checkedGoodsList;
                    var freightTempArray = Context.Queryable<tb_freight_template>()
                        .Where(s => s.is_delete == 0)
                        .ToList();
                    List<DTOFreightData> freightData = new List<DTOFreightData>();
                    for (int i = 0; i < freightTempArray.Count; i++)
                    {
                        freightData.Add(new DTOFreightData()
                        {
                            id = freightTempArray[i].id,
                            number = 0,
                            money = 0,
                            goods_weight = 0,
                            freight_type = freightTempArray[i].freight_type.Value
                        });
                    }

                    // 按件计算和按重量计算的区别是：按件，只要算goods_number就可以了，按重量要goods_number*goods_weight
                    // checkedGoodsList = [{goods_id:1,number5},{goods_id:2,number:3},{goods_id:3,number:2}]
                    foreach (var item in freightData)
                    {
                        foreach (var cartItem in cartGoods)
                        {
                            if (item.id == cartItem.freight_template_id)
                            {
                                // 这个在判断，购物车中的商品是否属于这个运费模版，如果是，则加一，但是，这里要先判断下，这个商品是否符合满件包邮或满金额包邮，如果是包邮的，那么要去掉
                                item.number = item.number + cartItem.number.Value;
                                item.money = item.money + cartItem.number.Value * cartItem.retail_price.Value;
                                item.goods_weight = item.goods_weight + cartItem.number.Value * cartItem.goods_weight.Value;
                            }
                        }
                    }
                    checkedAddress.full_region = string.Join("",
                        Context.Queryable<tb_region>()
                        .In(new int?[] { checkedAddress.province_id, checkedAddress.city_id, checkedAddress.district_id })
                        .OrderBy(s => s.id)
                        .Select(s => s.name).ToArray());

                    foreach (var item in freightData)
                    {
                        if (item.number == 0)
                        {
                            continue;
                        }


                        var ex = Context.Queryable<tb_freight_template_detail>()
                            .Where(s => s.template_id == item.id && s.area == province_id && s.is_delete == 0)
                            .First();
                        decimal? freight_price = 0;

                        if (ex != null)
                        {
                            // console.log('第一层：非默认邮费算法');
                            var groupData = Context.Queryable<tb_freight_template_group>()
                                .Where(s => s.id == ex.group_id)
                                .First();
                            // 不为空，说明有模板，那么应用模板，先去判断是否符合指定的包邮条件，不满足，那么根据type 是按件还是按重量
                            var free_by_number = groupData.free_by_number;
                            var free_by_money = groupData.free_by_money;
                            // 4种情况，1、free_by_number > 0  2,free_by_money > 0  3,free_by_number free_by_money > 0,4都等于0
                            var templateInfo = Context.Queryable<tb_freight_template>()
                                .Where(s => s.id == item.id && s.is_delete == 0)
                                .First();

                            var freight_type = templateInfo.freight_type;
                            if (freight_type == 0)
                            {
                                if (item.number > groupData.start)
                                { // 说明大于首件了
                                    freight_price = (groupData.start * groupData.start_fee) + (item.number - 1) * groupData.add_fee; // todo 如果续件是2怎么办？？？
                                }
                                else
                                {
                                    freight_price = groupData.start * groupData.start_fee;
                                }
                            }
                            else if (freight_type == 1)
                            {
                                if (item.goods_weight > groupData.start)
                                { // 说明大于首件了
                                    freight_price = groupData.start * groupData.start_fee + (item.goods_weight - 1) * groupData.add_fee; // todo 如果续件是2怎么办？？？
                                }
                                else
                                {
                                    freight_price = groupData.start * groupData.start_fee;
                                }
                            }
                            if (free_by_number > 0)
                            {
                                if (item.number >= free_by_number)
                                {
                                    freight_price = 0;
                                }
                            }
                            if (free_by_money > 0)
                            {
                                if (item.money >= free_by_money)
                                {
                                    freight_price = 0;
                                }
                            }
                        }
                        else
                        {
                            // console.log('第二层：使用默认的邮费算法');
                            var groupData = Context.Queryable<tb_freight_template_group>()
                                .Where(s => s.template_id == item.id && s.area == "0")
                                .First();


                            var free_by_number = groupData.free_by_number;
                            var free_by_money = groupData.free_by_money;
                            var templateInfo = Context.Queryable<tb_freight_template>()
                                .Where(s => s.id == item.id && s.is_delete == 0)
                                .First();


                            var freight_type = templateInfo.freight_type;
                            if (freight_type == 0)
                            {
                                if (item.number > groupData.start)
                                { // 说明大于首件了
                                    freight_price = groupData.start * groupData.start_fee + (item.number - 1) * groupData.add_fee; // todo 如果续件是2怎么办？？？
                                }
                                else
                                {
                                    freight_price = groupData.start * groupData.start_fee;
                                }
                            }
                            else if (freight_type == 1)
                            {
                                if (item.goods_weight > groupData.start)
                                { // 说明大于首件了
                                    freight_price = groupData.start * groupData.start_fee + (item.goods_weight - 1) * groupData.add_fee; // todo 如果续件是2怎么办？？？
                                }
                                else
                                {
                                    freight_price = groupData.start * groupData.start_fee;
                                }
                            }
                            if (free_by_number > 0)
                            {
                                if (item.number >= free_by_number)
                                {
                                    freight_price = 0;
                                }
                            }
                            if (free_by_money > 0)
                            {
                                if (item.money >= free_by_money)
                                {
                                    freight_price = 0;
                                }
                            }
                        }
                        freightPrice = freightPrice > freight_price ? freightPrice : freight_price;
                    }

                }
                else
                {

                }

                // 计算订单的费用
                var goodsTotalPrice = cartData.checkedGoodsAmount; // 商品总价
                                                                   // 获取是否有可用红包
                var money = cartData.checkedGoodsAmount;

                var orderTotalPrice = money + freightPrice; // 订单的总价
                var actualPrice = orderTotalPrice; // 减去其它支付的金额后，要实际支付的金额
                var numberChange = cartData.numberChange;
                orderTotalPrice = Math.Round(orderTotalPrice.Value, 2, MidpointRounding.AwayFromZero);
                actualPrice = Math.Round(actualPrice.Value, 2, MidpointRounding.AwayFromZero);
                if (checkedAddress == null)
                {
                    res.data = new
                    {
                        checkedAddress = 0,
                        freightPrice = freightPrice,
                        checkedGoodsList = checkedGoodsList,
                        goodsTotalPrice = goodsTotalPrice,
                        orderTotalPrice = orderTotalPrice,
                        actualPrice = actualPrice,
                        goodsCount = goodsCount,
                        outStock = outStock,
                        numberChange = numberChange
                    };
                }
                else
                {
                    res.data = new
                    {
                        checkedAddress = checkedAddress,
                        freightPrice = freightPrice,
                        checkedGoodsList = checkedGoodsList,
                        goodsTotalPrice = goodsTotalPrice,
                        orderTotalPrice = orderTotalPrice,
                        actualPrice = actualPrice,
                        goodsCount = goodsCount,
                        outStock = outStock,
                        numberChange = numberChange
                    };
                }


                return res;
            }
            catch (Exception ex)
            {
                res.errno = -1;
                res.errmsg = ex.Message;
                throw ex;
            }
        }

        private void addAgain(int? goods_id, int? product_id, int? number)
        {
            var currentTime = DateTimeExtensions.ConvertToUnixTimestamp(DateTime.Now);
            var goodsInfo = Context.Queryable<tb_goods>()
               .Where(s => s.id == goods_id)
               .First();
            if (goodsInfo == null || goodsInfo.is_on_sale == 0)
            {
                res.errno = 400;
                res.errmsg = "商品已下架";
                return;
            }
            // 取得规格的信息,判断规格库存
            var productInfo = Context.Queryable<tb_product>()
                  .Where(s => s.id == product_id)
                  .First();

            if (productInfo == null || productInfo.goods_number < number)
            {
                res.errno = 400;
                res.errmsg = "库存不足";
                return;
            }
            // 判断购物车中是否存在此规格商品
            var cartInfo = Context.Queryable<tb_cart>()
                .Where(s => s.user_id == uid && s.product_id == product_id && s.is_delete == 0)
                .First();
            decimal? retail_price = productInfo.retail_price;
            if (cartInfo == null)
            {

                // 添加操作
                // 添加规格名和值
                string[] listGoodsSpecification = { };
                if (!string.IsNullOrEmpty(productInfo.goods_specification_ids))
                {
                    listGoodsSpecification = Context.Queryable<tb_goods_specification>()
                      .Where(s => s.goods_id == productInfo.goods_id && s.is_delete == 0)
                      .In(s => s.id, productInfo.goods_specification_ids.Split('_'))
                      .Select(s => s.value).ToArray();
                }

                Insert(new tb_cart()
                {
                    goods_id = productInfo.goods_id,
                    product_id = product_id,
                    goods_sn = productInfo.goods_sn,
                    goods_name = goodsInfo.name,
                    goods_aka = productInfo.goods_name,
                    goods_weight = productInfo.goods_weight,
                    freight_template_id = (int)goodsInfo.freight_template_id,
                    list_pic_url = goodsInfo.list_pic_url,
                    number = number,
                    user_id = uid,
                    retail_price = retail_price,
                    add_price = retail_price,
                    goods_specifition_name_value = string.Join(";", listGoodsSpecification),
                    goods_specifition_ids = productInfo.goods_specification_ids,
                    @checked = 1,
                    add_time = (int)currentTime
                });

            }
            else
            {
                // 如果已经存在购物车中，则数量增加
                if (productInfo.goods_number < (number + cartInfo.number))
                {
                    res.errno = 400;
                    res.errmsg = "库存都不够啦";
                    return;
                }
                var tc = Context.Queryable<tb_cart>()
                      .Where(s => s.user_id == uid && s.product_id == product_id && s.is_delete == 0 && s.id == cartInfo.id)
                      .First();
                tc.retail_price = retail_price;
                tc.@checked = 1;
                tc.number = number;
                Update(tc);

            }

        }
        private DTOCart getAgainCart(int orderFrom)
        {
            List<tb_order_goods> againGoods = Context.Queryable<tb_order_goods>()
                .Where(s => s.order_id == orderFrom)
                .ToList();


            Context.Queryable<tb_cart>()
                .Where(s => s.user_id == uid && s.is_delete == 0)
                .First();
            int num = Context.Updateable<tb_cart>()
                 .Where(s => s.user_id == uid && s.is_delete == 0)
                 .ExecuteCommand();
            foreach (tb_order_goods item in againGoods)
            {
                addAgain(item.goods_id, item.product_id, item.number);
            }
            var cartList = Context.Queryable<tb_cart>()
                .Where(s => s.user_id == uid && s.is_fast == 0 && s.is_delete == 0)
                .ToList();

            //    // 获取购物车统计信息
            int? goodsCount = 0;
            decimal? goodsAmount = 0;
            int? checkedGoodsCount = 0;
            decimal? checkedGoodsAmount = 0;

            foreach (var cartItem in cartList)
            {
                goodsCount += cartItem.number;
                goodsAmount += cartItem.number * cartItem.retail_price;
                if (cartItem.@checked == 1)
                {
                    checkedGoodsCount += cartItem.number;
                    checkedGoodsAmount += cartItem.number * cartItem.retail_price;
                }
                // 查找商品的图片
                var info = Context.Queryable<tb_goods>()
                    .Where(s => s.id == cartItem.goods_id)
                    .First();

                var snum = info.goods_number;

                if (snum <= 0)
                {
                    var tc = Context.Queryable<tb_cart>()
                        .Where(s => s.product_id == cartItem.product_id
                        && s.user_id == uid
                        && s.@checked == 1
                        && s.is_delete == 0).First();
                    Update(tc);
                }

                cartItem.list_pic_url = info.list_pic_url;
                cartItem.number = info.goods_number;
                cartItem.goods_weight = cartItem.number * cartItem.goods_weight;

            }
            var cAmount = Math.Round(checkedGoodsAmount.Value, 2, MidpointRounding.AwayFromZero);
            goodsAmount = Math.Round(goodsAmount.Value, 2, MidpointRounding.AwayFromZero);

            return new DTOCart()
            {
                listCart = cartList,
                goodsCount = goodsCount,
                goodsAmount = goodsAmount,
                checkedGoodsCount = checkedGoodsCount,
                checkedGoodsAmount = cAmount,
                user_id = uid
            };
        }


        /// <summary>
        /// 获取购物车信息，所有对购物车的增删改操作，都要重新返回购物车的信息
        /// </summary>
        /// <param name="type">类型</param> 
        public DTOCart GetCart(int type)
        {
            try
            {
                List<tb_cart> listCart = new List<tb_cart>();

                if (type == 0)
                {
                    listCart = Context.Queryable<tb_cart>()
                        .Where(s => s.user_id == uid && s.is_delete == 0 && s.is_fast == 0)
                        .ToList();
                }
                else
                {
                    listCart = Context.Queryable<tb_cart>()
                        .Where(s => s.user_id == uid && s.is_delete == 0 && s.is_fast == 1)
                        .ToList();
                }
                // 获取购物车统计信息
                int? goodsCount = 0;
                decimal? goodsAmount = 0;
                int? checkedGoodsCount = 0;
                decimal? checkedGoodsAmount = 0;
                int numberChange = 0;
                tb_cart cart;
                foreach (tb_cart cartItem in listCart)
                {
                    cart = new tb_cart();
                    var pro = Context.Queryable<tb_product>()
                         .Where(s => s.id == cartItem.product_id && s.is_delete == 0).First();
                    if (pro == null)
                    {
                        cart = Context.Queryable<tb_cart>()
                         .Where(s => s.product_id == cartItem.product_id && s.user_id == uid && s.is_delete == 0)
                         .First();
                        cart.is_delete = 1;
                        Update(cart);
                    }
                    else
                    {
                        var retail_price = pro.retail_price;
                        var productNum = pro.goods_number;

                        if (productNum <= 0 || pro.is_on_sale == 0)
                        {
                            cart = Context.Queryable<tb_cart>()
                          .Where(s => s.product_id == cartItem.product_id
                          && s.user_id == uid
                          && s.is_delete == 0
                          && s.@checked == 1)
                          .First();
                            cart.@checked = 0;
                            Update(cart);
                            cartItem.number = 0;
                        }
                        else if (productNum > 0 && productNum < cartItem.number)
                        {
                            cartItem.number = productNum;
                            numberChange = 1;
                        }
                        else if (productNum > 0 && cartItem.number == 0)
                        {
                            cartItem.number = 1;
                            numberChange = 1;
                        }
                        goodsCount += cartItem.number;
                        goodsAmount += cartItem.number * retail_price;
                        cartItem.retail_price = retail_price;

                        if (cartItem.@checked == 1 && productNum > 0)
                        {
                            checkedGoodsCount += cartItem.number;
                            checkedGoodsAmount += cartItem.number * retail_price;
                        }

                        string url = Context.Queryable<tb_goods>()
                              .Where(s => s.id == cartItem.goods_id)
                              .First().list_pic_url;

                        cartItem.list_pic_url = url;
                        //cartItem.weight_count = cartItem.number * (int)cartItem.goods_weight;


                        cart = Context.Queryable<tb_cart>()
                         .Where(s => s.product_id == cartItem.product_id
                         && s.user_id == uid
                         && s.is_delete == 0)
                         .First();
                        cartItem.is_on_sale = pro.is_on_sale;


                        cart.number = cartItem.number;
                        cart.add_price = retail_price;
                        cart.is_on_sale = pro.is_on_sale;
                        Update(cart);
                    }
                }
                var cAmount = Math.Round(checkedGoodsAmount.Value, 2, MidpointRounding.AwayFromZero);
                goodsAmount = Math.Round(goodsAmount.Value, 2, MidpointRounding.AwayFromZero);
                DTOCart dc = new DTOCart();
                dc.listCart = listCart;
                dc.goodsCount = goodsCount;
                dc.goodsAmount = goodsAmount;
                dc.checkedGoodsCount = checkedGoodsCount;
                dc.checkedGoodsAmount = cAmount;
                dc.user_id = uid;
                dc.numberChange = numberChange;


                return dc;
            }
            catch (Exception ex)
            {
                res.errno = -1;
                res.errmsg = ex.Message;
                throw ex;
            }

        }

        /// <summary>
        /// 获取购物车商品的总件件数
        /// </summary>
        /// <param name="type">类型</param>
        /// <returns></returns>
        public ResponseMessage GetGoodsCartCount(int type)
        {
            try
            {
                DTOCart dc = GetCart(type);

                tb_cart cart = Context.Queryable<tb_cart>()
                    .Where(s => s.user_id == uid && s.is_delete == 0 && s.is_fast == 1).First();
                if (cart != null)
                {
                    cart.is_delete = 1;
                    Update(cart);
                }

                dynamic dd = new
                {
                    cartTotal = new
                    {
                        goodsCount = dc.goodsCount
                    }
                };
                res.data = dd;
                return res;
            }
            catch (Exception ex)
            {
                res.errno = -1;
                res.errmsg = ex.Message;
                throw ex;
            }
        }


        /// <summary>
        /// 清空已购买的商品
        /// </summary>
        /// <returns></returns>
        public bool ClearBuyGoods()
        {
            try
            {
                var res = Context.Queryable<tb_cart>()
                     .Where(s => s.user_id == uid && s.is_delete == 0 && s.@checked == 1)
                     .ToList();
                foreach (var item in res)
                {
                    item.is_delete = 1;
                }
                return UpdateRange(res);
            }
            catch (Exception ex)
            {
                res.errno = 400;
                res.errmsg = ex.Message;
                throw ex;
            }
        }

        /// <summary>
        /// 更新购物车的商品
        /// </summary>
        /// <param name="productId"></param>
        /// <param name="id"></param>
        /// <param name="number"></param>
        /// <returns></returns>
        public ResponseMessage UpdateOrderInfo(int productId, int id, int number)
        {
            try
            {
                // 取得规格的信息,判断规格库存
                var productInfo = Context.Queryable<tb_product>()
                    .Where(s => s.id == productId && s.is_delete == 0)
                    .First();


                if (productInfo == null || productInfo.goods_number < number)
                {
                    res.errno = 400;
                    res.errmsg = "库存不足";
                    return res;
                }


                // 判断是否已经存在product_id购物车商品
                var cartInfo = Context.Queryable<tb_cart>()
                    .Where(s => s.id == id && s.is_delete == 0)
                    .First();


                // 只是更新number
                if (cartInfo.product_id == productId)
                {
                    Context.Updateable<tb_cart>()
                        .Where(s => s.id == id && s.is_delete == 0)
                        .UpdateColumns(s => s.number == number)
                        .ExecuteCommand();

                    res.data = GetCart(0);
                    return res;
                }
                else
                {
                    return res;
                }
            }
            catch (Exception ex)
            {
                res.errno = 400;
                res.errmsg = ex.Message;
                return res;
            }
        }

        /// <summary>
        /// 删除购物车的商品
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        public ResponseMessage DeleteOrderInfo(int productId)
        {
            try
            {
                Context.Updateable<tb_cart>()
                    .Where(s => s.product_id == productId && s.user_id == uid && s.is_delete == 0)
                    .UpdateColumns(s => s.is_delete == 1)
                    .ExecuteCommand();


                res.data = GetCart(0);

                return res;
            }
            catch (Exception ex)
            {
                res.errno = 400;
                res.errmsg = ex.Message;
                return res;
            }
        }

    }
}
